package com.djq.hhc.template;

import com.djq.hhc.properties.MailProperties;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: dadd7
 * @Date: 2023/02/26/下午 3:03
 * @Description:
 */
public class MailTemplate {

    private MailProperties mailProperties;

    public MailTemplate(MailProperties mailProperties) {
        this.mailProperties = mailProperties;
    }

    public void sendMail(String toMailAddress, String code) {
        Properties properties = new Properties();
        properties.setProperty("mail.host", mailProperties.getHost());
        properties.setProperty("mail.smtp.auth", "true");
        Authenticator authenticator = new Authenticator(){
            @Override
            public javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mailProperties.getUsername(),mailProperties.getPassword());
            }
        };
        Session session = Session.getDefaultInstance(properties, authenticator);
        session.setDebug(true);
        Message message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(mailProperties.getFrom()));
            message.setRecipients(MimeMessage.RecipientType.TO,InternetAddress.parse(toMailAddress));
            //message.setRecipients(RecipientType.TO,InternetAddress.parse("测试的接收的邮件多个以逗号隔开"));
            try {
                message.setSubject("hhc验证码");
                message.setContent("你的验证码为：" + code + "，有效期5分钟。","text/html;charset=UTF-8");
                Transport.send(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
